package com.mbmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.common.constant.ProductConstant;
import com.mbmall.product.dao.AttrAttrgroupRelationDao;
import com.mbmall.product.dao.AttrGroupDao;
import com.mbmall.product.dao.CategoryDao;
import com.mbmall.product.entity.AttrAttrgroupRelationEntity;
import com.mbmall.product.entity.AttrGroupEntity;
import com.mbmall.product.entity.CategoryEntity;
import com.mbmall.product.service.CategoryService;
import com.mbmall.product.vo.AttrGroupRelationVo;
import com.mbmall.product.vo.AttrResVo;
import com.mbmall.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;

import com.mbmall.product.dao.AttrDao;
import com.mbmall.product.entity.AttrEntity;
import com.mbmall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao   attrAttrgroupRelationDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity=new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        //保存基本数据
        this.save(attrEntity);
        //保存关联关系
        if(attr.getAttrType()== ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()&&attr.getAttrGroupId()!=null){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity=new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }

    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> wrapper=new QueryWrapper<AttrEntity>().eq("attr_type",
                "base".equalsIgnoreCase(type)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if(catelogId!=0){
            wrapper.eq("catelog_id",catelogId);
        }
        String key=(String)params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((wap)->{
                wap.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        PageUtils pageUtils=new PageUtils(page);
        List<AttrEntity> records=page.getRecords();
        List<AttrResVo> reRecords=records.stream().map((attrEntity)->{
            AttrResVo attrResVo=new AttrResVo();
            BeanUtils.copyProperties(attrEntity,attrResVo);
            //设置分类和分组的名字
            if("base".equalsIgnoreCase(type)){

                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity=attrAttrgroupRelationDao.selectOne(
                        new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getAttrId()));
                if(attrAttrgroupRelationEntity!=null&&attrAttrgroupRelationEntity.getAttrGroupId()!=null){
                    Long groupId=attrAttrgroupRelationEntity.getAttrGroupId();
                    AttrGroupEntity attrGroup=attrGroupDao.selectById(groupId);
                    attrResVo.setGroupName(attrGroup.getAttrGroupName());
                }
            }

            CategoryEntity category=categoryDao.selectById(attrEntity.getCatelogId());
            attrResVo.setCatelogName(category.getName());
            return attrResVo;
        }).collect(Collectors.toList());

        pageUtils.setList(reRecords);
        return pageUtils;
    }

    @Override
    public AttrResVo getAttrInfo(Long attrId) {
        AttrResVo resVo=new AttrResVo();
        AttrEntity attrEntity=this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,resVo);



        //设置主体
        if(attrEntity.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity relationEntity=attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrId));
            if(relationEntity!=null){
                resVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroup=attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if(attrGroup!=null){
                    resVo.setGroupName(attrGroup.getAttrGroupName());
                }
            }
        }


        //设置分类信息 全路径
        Long[] paths=categoryService.findCategoryPath(attrEntity.getCatelogId());
        resVo.setCatelogPath(paths);
        CategoryEntity category=categoryDao.selectById(attrEntity.getCatelogId());
        if(category!=null){
            resVo.setCatelogName(category.getName());
        }

        return resVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        //首先修改基本数据
        AttrEntity attrEntity=new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);


        //修改分组关联
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity=new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attr.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());

            Long count= attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
            if(count>0){

                attrAttrgroupRelationDao.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
            }else{
                attrAttrgroupRelationDao.insert(relationEntity);
            }

        }


    }

    /**
     * 根据分组ID查询关联的所有基本信息
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities=attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id",attrgroupId));
        List<Long> attrIds=entities.stream().map((attr)->{
            return attr.getAttrId();
        }).collect(Collectors.toList());
        if(attrIds==null || attrIds.size()==0) {
            return null;
        }
        Collection<AttrEntity> attrEntities=this.listByIds(attrIds);
        return (List<AttrEntity>)attrEntities;
    }

    /**
     * 删除关联关系
     * @param vos
     */
    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityList=Arrays.asList(vos).stream().map((item)->{
            AttrAttrgroupRelationEntity relationEntity=new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item,relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteBatchRelation(attrAttrgroupRelationEntityList);
    }

    /**
     * 获取当前分组未关联所有属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //当前分组只能关联自己所属分类的所有属性
        AttrGroupEntity attrGroup = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroup.getCatelogId();
        //当前分组只能关联别的分组没有关联的属性，自己已关联
        //找到当前分类下的分组
        List<AttrGroupEntity> groups = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> collect = groups.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        //找到分组已关联的属性
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
        List<Long> attrIds = entities.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //从属性表中剔除这些属性
        QueryWrapper<AttrEntity> wrapper=new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(attrIds!=null && attrIds.size()>0){
            wrapper.notIn("attr_id", attrIds);
        }

        String key=(String)params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }

}